package gsfordservlet.repository;

import gsfordservlet.domain.GsfordEvent;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

/**
 *  
 * @author Kyungbaek Kim <kyungbaekkim@gmail.com>
 * @version 2012.0202 (YYYY.MMDD)
 * @since 1.6 (Java Version)
 */
public class JdbcGsfordEventDao extends SimpleJdbcDaoSupport {
    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    public List<GsfordEvent> getGsfordEventList() {
        logger.info("Getting GsfordEvents!");
        List<GsfordEvent> products = getSimpleJdbcTemplate().query(
                "select id, lblatitude, lblongitude, rtlatitude, rtlongitude, message, date from events", 
                new GsfordEventMapper());
        return products;
    }

    public void addGsfordEvent(GsfordEvent ge) {
        logger.info("Saving GsfordEvent: " + ge.toString());
        int count = getSimpleJdbcTemplate().update(
        	"insert into events (lblatitude, lblongitude, rtlatitude, rtlongitude, message, date) " +
        	"values (:lblatitude, :lblongitude, :rtlatitude, :rtlongitude, :message, :date)",
        	new MapSqlParameterSource().addValue("lblatitude", ge.getLblatitude())
        		.addValue("lblongitude", ge.getLblongitude())
        		.addValue("rtlatitude", ge.getRtlatitude())
        		.addValue("rtlongitude", ge.getRtlongitude())
        		.addValue("message", ge.getMessage())
        		.addValue("date", ge.getDate())
        	);            
        logger.info("Rows affected: " + count);
    }
    
    private static class GsfordEventMapper implements ParameterizedRowMapper<GsfordEvent> {

        public GsfordEvent mapRow(ResultSet rs, int rowNum) throws SQLException {
            GsfordEvent ge = new GsfordEvent();
            ge.setId(rs.getInt("id"));
            ge.setLblatitude(new Double(rs.getDouble("lblatitude")));
            ge.setLblongitude(new Double(rs.getDouble("lblongitude")));
            ge.setRtlatitude(new Double(rs.getDouble("rtlatitude")));
            ge.setRtlongitude(new Double(rs.getDouble("rtlongitude")));
            ge.setMessage(rs.getString("message"));
            ge.setDate(rs.getString("date"));            
            return ge;
        }

    }
}

